<template>
  <div class="password-edit">
    <van-nav-bar
      title="修改密码"
      left-text="返回"
      left-arrow
      @click-left="onBack"
      fixed
    />

    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="form.oldPassword"
          type="password"
          label="原密码"
          placeholder="请输入原密码"
          :rules="[{ required: true, message: '请输入原密码' }]"
        />
        <van-field
          v-model="form.newPassword"
          type="password"
          label="新密码"
          placeholder="请输入新密码"
          :rules="[
            { required: true, message: '请输入新密码' },
            { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/, 
              message: '密码至少8位，包含大小写字母和数字' }
          ]"
        />
        <van-field
          v-model="form.confirmPassword"
          type="password"
          label="确认密码"
          placeholder="请再次输入新密码"
          :rules="[
            { required: true, message: '请确认新密码' },
            { validator: validateConfirmPassword, message: '两次输入的密码不一致' }
          ]"
        />
      </van-cell-group>

      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          确认修改
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { updatePassword } from '@/api/doctor'
import { showSuccessToast, showFailToast } from 'vant'

const router = useRouter()
const userStore = useUserStore()

const form = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 验证确认密码
const validateConfirmPassword = (value) => {
  return value === form.value.newPassword
}

// 提交表单
const onSubmit = async () => {
  try {
    await updatePassword({
      oldPassword: form.value.oldPassword,
      newPassword: form.value.newPassword
    })
    showSuccessToast('密码修改成功，请重新登录')
    userStore.userLogout()
    router.replace('/login')
  } catch (error) {
    showFailToast(error.response?.data?.message || '修改失败')
  }
}

const onBack = () => {
  router.back()
}
</script>

<style lang="scss" scoped>
.password-edit {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-top: 46px;
}
</style> 